<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/8
 * Time: 13:56
 */
class RegisterBase extends ApiRedisBase
{
    public $isLogin = false;
    public $userRedis;

    public function __construct()
    {
        parent::__construct();
        $this->userRedis = $this->redis('user_info');
    }

    /**
     * 新建用户
     * @param $userInfo
     * @return mixed
     */
    protected function createNewUser($userInfo)
    {
        //生成用户信息
        $result = $this->userRedis->hMset("U:" . $userInfo['uid'], $userInfo);
        if ($result) {
            //生成UID和名称匹配关系
            $result = $this->userRedis->hMset("N:" . $userInfo["username"], ['uid' => $userInfo['uid']]);
        }

        return $result;
    }

    /**
     * 生成用户信息
     * @return array
     */
    protected function getUserInfo()
    {
        $uid = $this->selectUser();

        $now = time();
        $salt = $this->getSalt(6);
        $name = "mj" . $uid;

        $userInfo = array(
            'uid' => $uid,
            'username' => $name,
            'sex' => 0,
            'nickname' => $name,
            'avatar' => '',
            'address' => '',
            'password' => '',
            'salt' => $salt,
            'token' => md5($now . $salt),
            'status' => 1,
            'platform' => $this->platform,
            'channelID' => $this->channelId,
            'ver' => $this->ver,
            'imei' => $this->params['imei'],
            'imsi' => $this->params['imsi'],
            'mac' => $this->params['mac'],
            'model' => $this->params['model'],
            'freeDiamond' => (integer)GameConfig::$room_config['default_diamonds'], //免费房卡
            'paidDiamond' => 0, //付费房卡
            'registerIP' => IP::getClientIP(), //注册时的IP
            'registerTime' => $now
        );

        return $userInfo;
    }

    /**
     * 生成用户额外信息
     * @param $userInfo
     * @return mixed
     */
    public function getExtraInfo($userInfo)
    {
        $userInfo['IP'] = IP::getClientIP();

        if ($userInfo) {
            //获取房间信息
            $userQuery = new UserQuery();
            $roomInfo = $userQuery->queryRoomInfo($userInfo['uid'], $this->platform);
            if ($roomInfo) {
                $userInfo['roomInfo'] = $roomInfo;
            }
        }

        unset(
            $userInfo['imei'], $userInfo['imsi'], $userInfo['mac'],
            $userInfo['model'], $userInfo['salt'], $userInfo['password']
        );

        return $userInfo;
    }

    /**
     * 用户信息部分字段处理
     * @param $userInfo
     * @return mixed
     */
    protected function afterUserInfo($userInfo)
    {
        $userInfo['diamond'] = $userInfo['freeDiamond'] + $userInfo['paidDiamond'];
        return $userInfo;
    }

    /**
     * 登录之后处理
     * @param $userInfo
     */
    public function afterLogin($userInfo)
    {
        $this->saveToken($userInfo);
        $this->loginStastic($userInfo);
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return array|mixed
     */
    public function getUser($uid)
    {
        $key = "U:$uid";

        if (!$this->userRedis->exists($key)) {
            $this->logWarning('no_user');
            return array();
        }

        $userQuery = new UserQuery();
        $userInfo  = $userQuery->getUserInfo($uid, $this->platform, ['token']);
        return $userInfo;
    }

    /**
     * 保存token到token库，供游戏服务器登录验证
     * @param $userInfo
     */
    public function saveToken($userInfo)
    {
        $key = 'userKey' . $userInfo['uid'];
        $redis = $this->redis('token');
        $result = $redis->set($key, $userInfo['token']);

        if (!$result) {
            $this->returnError('failed_login');
        }

        $expireTime = 30;
        if (GlobalConfig::$redis_expire['game_user_token']) {
            $expireTime = GlobalConfig::$redis_expire['game_user_token'];
        }

        $redis->expire($key, $expireTime);
    }

    /**
     * 用户在线统计
     * @param $userInfo
     */
    public function loginStastic($userInfo)
    {
        $userInfo['loginTime'] = time();

        //写入用户登录日志队列
        $loginLog = new LoginLogQueen();
        $data = [
            'uid' => $userInfo['uid'],
            'loginTime' => $userInfo['loginTime'],
            'platform'  => (integer)$this->platform,
            'channelID' => (integer)$this->channelId,
            'ver'       => $this->ver,
        ];
        $result = $loginLog->push($data);
        if (!$result) {
            $this->logWarning('failed_online_log', $data);
        }
    }

    /**
     * 从随机生成一个用户
     * @return bool|int
     */
    public function selectUser()
    {
        $userID = new UserID();
        $uid = $userID->generateUid();

        if ($uid === false) {
            $this->returnError('fault_uid');
        }

        return $uid;
    }

    /**
     * 获取Salt
     * @param $len
     * @return string
     */
    public function getSalt($len)
    {
        $salt = '';
        $str = GameConfig::$salt_password;
        $length = strlen($str)-1;
        for($i = 0;$i < $len;$i ++){
            $num = mt_rand(0, $length);
            $salt .= $str[$num];
        }
        return $salt;
    }

    /**
     * 注册成功后的处理
     * @param $userInfo
     */
    public function afterRegister($userInfo)
    {
        /**
         * 写入用户信息队列，供落地到Mysql
         */
        $data = $userInfo;
        unset($data['roomInfo']);
        $result = $this->redis('user_stats')->lpush(
            'registerLog',
            json_encode($data, JSON_UNESCAPED_UNICODE)
        );
        if (!$result) {
            $this->e('push_register_user_error', $userInfo);
        }

        /**
         * 写入赠送钻石队列，供落地到Mysql
         */
        try {
            $data = [
                'uid'          => $userInfo['uid'],
                'type'         => 0,
                'payType'      => 0,
                'actType'      => 0,
                'gameType'     => 0,
                'platform'     =>$this->platform,
                'channelID'    => $this->channelId,
                'version'      => $this->ver,
                'nickname'     => $userInfo['nickname'],
                'diamond'      => $userInfo['freeDiamond'],
                'oldDiamond'   => 0,
                'newDiamond'   => $userInfo['freeDiamond'],
                'desc'         => 'register_give',
                'createTime'   => time(),
            ];
            $queen = new DiamondLogQueen();
            $queen->push($data);
        } catch(Exception $e) {
            $this->e('push_diamond_log_error', $data);
        }
    }
}